<?php
	if($_SERVER["HTTPS"] != "on")
	{
		header("Location: https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
	}
	date_default_timezone_set('America/New_York');
	session_start();
	
	function setElementByID($elementID, $text)
	{
		echo "<script>";
		echo "document.getElementById('$elementID').innerHTML = '$text'";
		echo "</script>";
	}
	
	function concatElementByID($elementID, $text)
	{
		echo "<script>";
		echo "var current = document.getElementById('$elementID').innerHTML ;
				document.getElementById('$elementID').innerHTML = current + '$text'";
		echo "</script>";
	}
	
	function logoutCurrentUser()
	{
		destroySession();
		displayJavaScriptAlert("You have been logged out.");
		echo "success";
		// forgetRememberMeCookie();
	}
		
	function usernamePasswordPairExists($username, $password)
	{
		$username = sanitizeString($username);
		$password = sanitizeString($password);
		
		require("\private\mysqli_connect.php");
		$query = "select username, password from users";
		$result = $db->query($query);
		if(!$result):
			echo "<br/> No users have been added to the database. <br/>";
			return false;
		endif;
				
		$rows = $result->num_rows;
		$match = false;
		for($i = 0; $i < $rows; $i++):
			$row = $result->fetch_array();
			$current_username = $row['username'];
			$current_password = $row['password']; // SHA1
			// echo "Does username '$username' match '$current_username' <br/>";
			// echo "and Does password '$password' match '$current_password' <br/>";
			if(strcmp($current_username, $username) == 0 && strcmp($current_password, SHA1($password)) == 0):
				$match = true;
				break;
			else:
				continue;
			endif;
		endfor;
		if($match):
			echo "<br/>Successfully logged in as admin '$username'<br/>";
			return true;
		else:
			return false;
		endif;
	}
	
	function sanitizeString($text)
	{
		if(!isset($text) || empty($text)):
			return "";
		endif;
		/* Remove any whitespace and strip slashes */
		return stripslashes(preg_replace('/\s+/', '', $text));
	}
	
	function sanitizeStringKeepSpaces($text)
	{
		if(!isset($text) || empty($text)):
			return "";
		endif;
		/* Remove any whitespace and strip slashes */
		return trim(stripslashes($text));
	}
	
	function emptyUsernameOrPassword()
	{
		$elementID = "error";
		$usernameOrPasswordEmpty = "Please fill in your username and password.";
		include("login_form.html");
		concatElementByID($elementID, $usernameOrPasswordEmpty);
	}
	
	function successfulLogin($username)
	{
		destroySession(); // clean up any lingering session data
		session_start();
		$_SESSION['username'] = $username;
		$_SESSION['userID'] = getUserIDbyName($username);
		$_SESSION['userIsAdmin'] = userIsAdmin($username);
		//createUserCookie($username);
		redirectUserToUserPage();
	}
	
	function getUserIDbyName($userName)
	{
		require('\private\mysqli_connect.php');
		$query = "select users.user_id from users where username = '" . $userName . "'";
		$result = $db->query($query);
		if($result):
			$row = $result->fetch_array();
			return $row['user_id'];
		else:
			return "";
		endif;
	}
	
	function userIsAdminInSession()
	{
		if(!isset($_SESSION['userIsAdmin'])):
			return false;
		else:		
			return $_SESSION['userIsAdmin'];
		endif;
	}
	
	function userIsAdmin($userName)
	{
		require('\private\mysqli_connect.php');
		$query = "select users.user_id from users where username = '" . $userName . "' and is_admin = true";
		$result = $db->query($query);
		if($result):
			if($result->num_rows):
				return true;
			else:
				return false;
			endif;
		else:
			return false;
		endif;
	}
	
	function unsuccessfulLogin()
	{
		if(isset($_SESSION)):
			session_destroy();
		endif;		
		$elementID = "error";
		$errorMessage = "Username / password combo did not match. <br />";
		include("login_form.html");		
		concatElementByID($elementID, $errorMessage);
	}
	
	function login($username, $password)
	{
		
		$username = sanitizeString($username);
		$password = sanitizeString($password);
		// if(strcmp($username,'') == 0 || strcmp($password,'') == 0):
		if(empty($username) || empty($password)):
			emptyUsernameOrPassword();
		else:
			if(usernamePasswordPairExists($username, $password)):
				successfulLogin($username);
			else:
				unsuccessfulLogin($username);
			endif;
		endif;
	}
	
	/* 	Create a new user in the data --
		This user is not an admin since we assume admins are added manually and
		not through the register page. */
		// TODO: make sure this works
	function createUser($username, $password, $email)
	{
		$username = sanitizeString($username);
		$password = sanitizeStringKeepSpaces($password);
		$email = sanitizeString($email);
		if($username && $password && $email):
			if(usernameIsUnique($username) && emailIsUnique($email)):
				if(addNonAdminUser($username, $password, $email)):
					displayJavaScriptAlert("Added user '$username'");
				else:
					displayJavaScriptAlert("Unable to add user'$username'");
				endif;
			else:
				displayJavaScriptAlert("The username and email need to be unique.");
			endif;
		else:
			displayJavaScriptAlert("Please enter all fields.");
		endif;
	}
	
	function addNonAdminUser($username, $password, $email)
	{
		$username = sanitizeString($username);
		$password = sanitizeStringKeepSpaces($password);
		$email = sanitizeString($email); // should already be in form cmb155+cameron@pitt.edu
		
		require("\private\mysqli_connect.php");
		// insert into users(is_admin, password, username, email) values(true, SHA1('katniss'), 'Katniss', 'cmb155+katniss@pitt.edu'); 
		// $email = $PITTusername . '+' . $username . '@pitt.edu'; // cmb155+cameron@pitt.edu
		$query = "insert into users(is_admin, password, username, email) values(false, SHA1('$password'), '$username', '$email'); ";
		$result = $db->query($query);
		if(!$result):
			echo "<br/>Unable to insert new user '$username'.<br/>";			
			return false;
		else:
			return true;
		endif;
	}
	
	function usernameIsUnique($username)
	{
		$username = sanitizeString($username);
				
		require("\private\mysqli_connect.php");
		$query = "select username from users";
		$result = $db->query($query);
		if(!$result):
			echo "<br/> No users have been added to the database. <br/>";
			return true;
		endif;
				
		$rows = $result->num_rows;
		$match = false;
		for($i = 0; $i < $rows; $i++):
			$row = $result->fetch_array();
			$current_username = $row['username'];
			if(strcmp($current_username, $username) == 0):
				$match = true;
				break;
			else:
				continue;
			endif;
		endfor;
		if($match):
			echo "<br/>Username '$username' already exists.<br/>";
			return false;
		else:
			echo "<br/>Username '$username' does not exist.<br/>";
			return true;
		endif;
	}
	
	function emailIsUnique($email)
	{
		$email = sanitizeString($email);
				
		require("\private\mysqli_connect.php");
		$query = "select email from users";
		$result = $db->query($query);
		if(!$result):
			echo "<br/> No users have been added to the database. <br/>";
			return true;
		endif;
				
		$rows = $result->num_rows;
		$match = false;
		for($i = 0; $i < $rows; $i++):
			$row = $result->fetch_array();
			$current_email = $row['email'];
			if(strcmp($current_email, $email) == 0):
				$match = true;
				break;
			else:
				continue;
			endif;
		endfor;
		if($match):
			echo "<br/>Email '$email' already exists.<br/>";
			return false;
		else:
			echo "<br/>Email '$email' does not exist.<br/>";
			return true;
		endif;
	}
	
	function createUserCookie($username)
	{
		$timeOffset = 24*60*60*20;
		if(isset($_POST['stayLoggedIn'])):
			setcookie("$username" . "['username']", "$username",time() + $timeOffset, "/");
			setcookie("$username" . "['stayLoggedIn']",1, time() + $timeOffset, "/");
			setcookie("lastRememberedLogin", $username, time() + $timeOffset, "/");
		else:
			setcookie("$username" . "['username']", "$username",time() + $timeOffset, "/");
			setcookie("$username" . "['stayLoggedIn']",0, time() + $timeOffset, "/");
			/* Someone new logged in. Make sure we forget them */
			setcookie("lastRememberedLogin", "", time() - 50000, "/");
		endif;		
	}
	
	function forgetRememberMeCookie()
	{
		setcookie("lastRememberedLogin","", time() - 50000, "/");
	}
	
	function adminIsLoggedIn()
	{
		if(!isset($_SESSION)):
			session_start();
		endif;
		// $cookieFound = false;
		// if(isset($_COOKIE['lastRememberedLogin']) && !(strcmp($_COOKIE['lastRememberedLogin'], "") == 0)):
			// $username = $_COOKIE['lastRememberedLogin'];

			// $cookieFound = true;
			
			// $_SESSION['admin_username'] = $username;
			// return true;
		// else:
			// /* No one was found to be logged in with a cookie */
		// endif;		
		if(isset($_SESSION['username']) and !empty($_SESSION['username'])):
			return true;
		else:
			return false;
		endif;
		
		return false;
	}
	
	function redirectUserToUserPage()
	{
		header("Location: /proj3/main.php");
	}
	
	function destroySession()
	{
		session_destroy();
		
		echo "Killing session and cookies. <br />";
		var_dump($_SESSION);
		var_dump($_COOKIE);
		header("Location: /proj3/login.php");
	}
	
	function displayJavascriptAlert($message)
	{
		echo "<script>";
		echo 'alert("' . $message . '");';
		echo "</script>";
	}
?>